﻿using System;
using System.Web.UI;

namespace Evpo.ContactData.CustomControls
{
    internal class LookupTools
    {
        internal LookupTools(ILookupControl lookupControl)
        {
            LookupHost = FindHost(lookupControl);
            if (LookupHost == null)
                LookupHost = new DummyLookupHost();

            LookupHost.RegisterLookupControl(lookupControl);
        }


        #region Properties
        internal ILookupHost LookupHost
        {
            get;
            private set;
        }
        #endregion

        #region Events
        internal event SelectedItemsEventHandler GetSelectedItems
        {
            add
            {
                LookupHost.GetSelectedItems += value;
            }

            remove
            {
                LookupHost.GetSelectedItems -= value;
            }
        }

        internal event SelectedItemsEventHandler SetSelectedItems
        {
            add
            {
                LookupHost.SetSelectedItems += value;
            }

            remove
            {
                LookupHost.SetSelectedItems -= value;
            }
        }


        #endregion Events

        #region Fields

        #endregion


        #region Methods

        private ILookupHost FindHost(ILookupControl lookupControl)
        {
            Control cnt = lookupControl.Parent;
            ILookupHost host = null;
            while ((host = cnt as ILookupHost) == null && cnt != null)
                cnt = cnt.Parent;

            return host;
        }

        #endregion Methods

        #region Classes
        private class DummyLookupHost : ILookupHost
        {
            public event SelectedItemsEventHandler GetSelectedItems;
            public event SelectedItemsEventHandler SetSelectedItems;


            public void RegisterLookupControl(ILookupControl cnt)
            {
            }
        }
        #endregion Classes
    }
}
